package com.sba.core.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sba.core.domain.Menu;
import com.sba.core.service.MenuService;

/**
 * 
 * @author feiliming
 *
 */
@Controller
@RequestMapping("${ssh.admin-path}/menu")
public class MenuController extends BaseController {

	private final MenuService menuService;
	
	@Autowired
	public MenuController(MenuService menuService){
		this.menuService = menuService;
	}
	
	@GetMapping
	public String index(Map<String, Object> model){
		return adminThemePath + "/sys/menu";
	}
	
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	public @ResponseBody List<Menu> getMenus(Long parentId, boolean isContainSub){
		List<Menu> menus = new ArrayList<Menu>();
		if(parentId != null){
			menus = menuService.getMenus(parentId, isContainSub);
		}else {
			menus = menuService.getMenus();
		}
		return menus;
	}
	
	@PostMapping("/save")
	public @ResponseBody JSONObject saveMenu(Menu menu){
		menu.setCreateTime(new Date());
		JSONObject obj = new JSONObject();
		try {
			menuService.saveOrUpdate(menu);
			obj.put("success", true);
			obj.put("msg", "保存菜单成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "保存菜单失败！");
		}
		return obj;
	}
	
	@GetMapping("/get")
	public @ResponseBody Menu getMenu(Long id){
		return menuService.getById(id);
	}
	
	@RequestMapping(path = "/delete", method = RequestMethod.POST)
	public @ResponseBody JSONObject deleteMenu(Long id){
		Menu menu = menuService.getById(id);
		JSONObject obj = new JSONObject();
		if(menu.getIsLeaf() != 1){
			obj.put("success", false);
			obj.put("msg", "该菜单非叶子节点，禁止删除！");
			return obj;
		}else if(menu.getRoles().size() > 0){
			obj.put("success", false);
			obj.put("msg", "该菜单已经分配给角色，禁止删除！");
			return obj;
		}else{
			try {
				menuService.delete(id);
				obj.put("success", true);
				obj.put("msg", "删除菜单成功！");
			} catch (Exception e) {
				obj.put("success", false);
				obj.put("msg", "删除菜单失败！");
			}
			return obj;
		}
	}
}
